package cn.tank.rabbitwork.service.impl;

import cn.tank.rabbitwork.config.RabbitConfig;
import cn.tank.rabbitwork.dao.OrderRepository;
import cn.tank.rabbitwork.entity.Order;
import cn.tank.rabbitwork.entity.OrderDetail;
import cn.tank.rabbitwork.entity.OrderStatus;
import cn.tank.rabbitwork.service.IMQService;
import cn.tank.rabbitwork.service.IOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IMQService mqService;
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RabbitConfig rabbitConfig;

    @Override
    public void addOrder(Order order) {
        if(order==null || order.getOrderDetails()==null || order.getOrderDetails().size() == 0){
            return ;
        }
        double total = 0.0;
        for (OrderDetail orderDetail : order.getOrderDetails()) {
            total += orderDetail.getPrice() * orderDetail.getNums();
            orderDetail.setOrder(order);
        }
        order.setTotal(total);
        order.setCreateTime(new Date());
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setStatus(0);
        order.setOrderStatus(orderStatus);
        //存储
        order = orderRepository.save(order);

        //支付队列
        mqService.sendOrderSaveMsg(order);
    }

    @Override
    public void overtime(Order order) {
        //查询是否已经支付
        Optional<Order> byId = orderRepository.findById(order.getId());

        if(byId.get()==null || byId.get().getOrderStatus().getStatus()!=0){
            return;
        }

        order.setLastUpdateTime(new Date());
        //超时-未支付
        order.getOrderStatus().setStatus(2);

        orderRepository.save(order);
    }



    @Override
    public List<Order> QueryOrder(String name) {
        List<Order> allByPsnName = orderRepository.findAllByPsnName(name);
        Date date = new Date();

        if (allByPsnName!=null){
            for (Order order : allByPsnName) {

                if(order.getOrderStatus().getStatus()==0){
                    //到期时间
                    long overTime = order.getCreateTime().getTime()+(rabbitConfig.expireTime*1000);
                    long nowTime = date.getTime();
                    long left = overTime-nowTime;

                    int min = (int)(left/1000)/60;
                    int sec = (int)(left/1000)%60;
                    order.setLeftTime(min+"分"+sec+"秒");
                }

            }
        }
        return allByPsnName;
    }
}
